<template>
  <view class="question-page">
    <view class="page-header">
      <view class="avatar-box">
        <view class="avatar-image">
          <image src="/static/tab_bar/my_active.png" mode="aspectFill"></image>
        </view>
        <view class="interviewer-info">
          <text class="interviewer-name">{{ jobPosition }}</text>
          <text class="interviewer-role">面试者</text>
        </view>
      </view>
    </view>
    
    <view class="content">
      <swiper
        class="question-swiper"
        :current="currentIndex"
        @change="handleSwiperChange"
        :disable-touch="true"
        :style="swiperStyle"
      >
        <!-- 问题卡片 -->
        <swiper-item v-for="(question, index) in questions" :key="index" class="swiper-item">
          <view class="question-card">
            <view class="card-header">
              <text class="question-number">{{ String(index + 1).padStart(2, '0') }}</text>
            </view>
            
            <view class="question-content">
              <text class="question-text">{{ question.questionContent.slice(2) }}</text>
            </view>
            
            <view class="answer-area">
              <textarea
                v-model="answers[index]"
                placeholder="请在此输入您的回答..."
                class="answer-input"
                :disable-default-padding="true"
                :auto-height="true"
                :maxlength="-1"
              ></textarea>
            </view>
            
            <view class="card-footer">
              <button 
                class="prev-btn" 
                :disabled="index === 0"
                @click="prevQuestion"
              >上一题</button>
              
              <button 
                class="next-btn" 
                :disabled="!answers[index]"
                @click="nextQuestion"
              >
                {{ index === questions.length - 1 ? '下一步' : '下一题' }}
              </button>
            </view>
          </view>
        </swiper-item>
        
        <!-- 最后一页 - 完成页 -->
        <swiper-item class="swiper-item">
          <view class="complete-card">
            <view class="complete-icon">✅</view>
            <text class="complete-title">恭喜你，已完成所有问答！</text>
            <text class="complete-desc">点击提交，查看面试结果分析</text>
            
            <view class="btn-group">
              <button class="prev-btn" style="border-radius: 40rpx;" @click="prevQuestion">返回</button>
              <button class="submit-btn" @click="submitAnswers">提交</button>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>
    
    <view class="loading-overlay" v-if="loading">
      <view class="loading-content">
        <text class="loading-text">正在生成面试问题...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import NavHeader from '@/components/nav-header.vue'
import { onLoad } from '@dcloudio/uni-app'
import { useInterviewStore } from '@/store/interview'
import { generateConversation, generateSampleQuestions, submitInterviewAnswers, submitInterviewAnswersBatch, updateInterviewDetail, getInterviewDetail } from '@/api/interview'
import { strFormatTime } from '@/utils/format'
import { getIndexInfo } from '@/api/edit/index'

const statusBarHeight = ref(20)
const currentIndex = ref(0)
const questions = ref([])
const answers = reactive({})
const loading = ref(true)
const resumeId = ref('')
const interviewStore = useInterviewStore()
const startDate = ref()
const endDate = ref()
const jobPosition = ref()

// 计算swiper高度样式
const swiperStyle = computed(() => {
  return {
    height: 'calc(100vh - 200rpx)'
  }
})

// 处理swiper切换
const handleSwiperChange = (e) => {
  currentIndex.value = e.detail.current
}

// 上一题
const prevQuestion = () => {
  console.log(currentIndex.value, 'currentIndex.value')
  if (currentIndex.value > 0) {
    currentIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (!answers[currentIndex.value]) {
    uni.showToast({
      title: '请输入回答',
      icon: 'none'
    })
    return
  }
  
  if (currentIndex.value < questions.value.length) {
    currentIndex.value++
  }
}

// 提交答案
const submitAnswers = async () => {
  let hasResult = false
  // 检查是否所有问题都已回答
  const unansweredIndex = questions.value.findIndex((_, index) => !answers[index])
  if (unansweredIndex !== -1) {
    uni.showToast({
      title: `第${unansweredIndex + 1}题未回答`,
      icon: 'none'
    })
    currentIndex.value = unansweredIndex
    return
  }
  endDate.value = strFormatTime(new Date())
  await updateInterview()

  // 构造提交数据
  await questions.value.forEach((question, index) => {
    question.answerContent = answers[index];
    question.askTime = strFormatTime(new Date())
  })
  // 模拟提交
  uni.showLoading({ title: '提交中...' })
  
  const detailRes = await getInterviewDetail(interviewStore.interviewId)
  if (detailRes.code === 200) {
    hasResult = detailRes.data.evaluation ? true : false
  }

  if (hasResult) {
    uni.hideLoading()
    uni.showToast({
      title: '已存在面试结果，请到历史详情页面查看',
      icon: 'none'
    })
    uni.navigateTo({
      url: `/pages/interview/historyDetail?interviewId=${interviewStore.interviewId}`
    })
  }else{
    const res = await submitInterviewAnswersBatch(questions.value)
    if (res.code === 200) {
      uni.hideLoading()
      uni.navigateTo({
        url: '/pages/interview/result?id='+interviewStore.interviewId+'&resumeId='+resumeId.value
      })
    }
  }
}

// 修改面试详情
const updateInterview = async () => {
  const res = await updateInterviewDetail({interviewId: interviewStore.interviewId, startTime: startDate.value, endTime: endDate.value})
}

// 获取面试问题
const fetchQuestions = async (id, interviewId) => {
  try {
    loading.value = true
    const res = await generateSampleQuestions({interviewId: interviewId})
    console.log(res, 'res')
    if (res.code === 200) {
      questions.value = res.data
      loading.value = false
      startDate.value = strFormatTime(new Date())
    }else{
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
        loading.value = false
      }, 1000)
    }
  } catch (error) {
    console.log(error, 'error')
    setTimeout(() => {
      uni.navigateBack()
      loading.value = false
    }, 1000)
  }
  //   // 模拟数据
  //   questions.value = [
  //     {
  //       id: '1',
  //       content: '请简单介绍一下你自己和你的工作经历。'
  //     },
  //     {
  //       id: '2',
  //       content: '你为什么对我们公司的这个职位感兴趣？'
  //     },
  //     {
  //       id: '3',
  //       content: '描述一个你在工作中遇到的挑战，以及你是如何解决的？'
  //     },
  //     {
  //       id: '4',
  //       content: '你认为自己的优势和不足是什么？'
  //     },
  //     {
  //       id: '5',
  //       content: '你对未来的职业规划是什么？'
  //     }
  //   ]
    
  //   loading.value = false
  // }, 2000)
}

const createTalk = async (id) => {
  const res = await generateConversation({resumeId: id})
  if (res.code === 200) {
    interviewStore.interviewId = res.data
    await fetchQuestions(id, interviewStore.interviewId)
    await getResumeInfo(id)
  }
}

const getResumeInfo = async (id) => {
  const res = await getIndexInfo(id)
  if (res.code === 200) {
    jobPosition.value = res.data.jobIntention.jobPosition
  }
}

onLoad(async (options) => {
  if (options.resumeId) {
    resumeId.value = options.resumeId
    await createTalk(resumeId.value)
  }
})

onMounted(() => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  
  // 获取页面参数
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  if (page.options && page.options.resumeId) {
    resumeId.value = page.options.resumeId
  }
  
  // 加载面试问题
  // fetchQuestions()
})
</script>

<style lang="scss" scoped>
.question-page {
  height: 100vh;
  background-color: #f5f7fb;
  position: relative;
  
  .page-header {
    padding: 20rpx 40rpx 30rpx;
    
    .avatar-box {
      display: flex;
      align-items: center;
      position: relative;
      
      .avatar-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 20%;
        background-color: #fff;
        margin-right: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        image{
          width: 70%;
          height: 70%;
        }
      }
      
      .interviewer-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        
        .interviewer-name {
          font-size: 34rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 6rpx;
        }
        
        .interviewer-role {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
  }
  
  .content {
    width: 100%;
    height: calc(100vh - 200rpx);
    padding: 20rpx 0;
    overflow: hidden;
  }
  
  .question-swiper {
    width: 100%;
    height: 100%;
    
    .swiper-item {
      display: flex;
      justify-content: center;
      height: 100%;
    }
  }
  
  .question-card {
    background-color: #fff;
    border-radius: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    width: 80vw;
    height: 90%;
    overflow-y: auto;
    
    .card-header {
      margin-bottom: 30rpx;
      
      .question-number {
        font-size: 80rpx;
        font-weight: bold;
        color: #333;
        opacity: 0.9;
      }
    }
    
    .question-content {
      padding: 0 0 30rpx;
      
      .question-text {
        font-size: 36rpx;
        color: #333;
        font-weight: 500;
        line-height: 1.5;
      }
    }
    
    .answer-area {
      flex: 1;
      margin-bottom: 30rpx;
      
      .answer-input {
        min-height: 400rpx;
        max-height: 600rpx;
        overflow-y: auto;
        background-color: #f8f9fc;
        border-radius: 20rpx;
        padding: 30rpx;
        font-size: 30rpx;
        color: #333;
        line-height: 1.6;
        width: auto;
      }
    }
    
    .card-footer {
      display: flex;
      justify-content: space-between;
      gap: 20rpx;
      
      button {
        flex: 1;
        height: 90rpx;
        line-height: 90rpx;
        text-align: center;
        border-radius: 45rpx;
        font-size: 30rpx;
        
        &.prev-btn {
          background-color: #f0f0f0;
          color: #666;
          
          &:disabled {
            opacity: 0.5;
          }
        }
        
        &.next-btn {
          background-color: #5ac725;
          color: #fff;
          
          &:disabled {
            opacity: 0.5;
          }
        }
      }
    }
  }
  
  .bottom-nav {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 20rpx 30rpx;
    background: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 10;
    
    .nav-button {
      flex: 1;
      height: 90rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      border-radius: 45rpx;
      margin: 0 10rpx;
      background-color: #f5f5f5;
      color: #666;
      
      &.primary {
        background-color: #5ac725;
        color: #fff;
      }
      
      &.disabled {
        opacity: 0.5;
      }
    }
  }
  
  .complete-card {
    width: 80vw;
    height: 90%;
    background-color: #fff;
    border-radius: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .complete-icon {
      font-size: 100rpx;
      margin-bottom: 40rpx;
    }
    
    .complete-title {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .complete-desc {
      font-size: 30rpx;
      color: #666;
      margin-bottom: 60rpx;
    }

    .btn-group {
      width: 100%;
      display: flex;
      justify-content: space-between;
      gap: 20rpx;

      .submit-btn {
        flex: 1;
        height: 90rpx;
        line-height: 90rpx;
        background-color: #5ac725;
        color: #fff;
        font-size: 32rpx;
        font-weight: 500;
        border-radius: 45rpx;
      }
    }
  }
  
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.95);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
    
    .loading-content {
      background-color: #fff;
      padding: 40rpx 60rpx;
      border-radius: 20rpx;
      box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.1);
      
      .loading-text {
        font-size: 30rpx;
        color: #333;
      }
    }
  }
}
</style> 